package net.bingosoft.common.struts.validator;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import net.bingosoft.common.BeanHelper;

import org.apache.commons.validator.Field;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.Resources;

/**
 * 
 * 2007-8-20 上午10:12:14
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:Struts扩展验证规则
 * ChangeLog:
 */
public class StrutsExtendFieldChecks {

	private static final long serialVersionUID = 1L;
	/**
	 * 日期验证,验证一个日期要早于另一个给定的日期
	 *
	 * @param bean The bean validation is being performed on.
	 * @param va The <code>ValidatorAction</code> that is currently being performed.
	 * @param field The <code>Field</code> object associated with the current
	 * field being validated.
	 * @param errors The <code>ActionMessages</code> object to add errors to if
	 * any validation errors occur.
	 * @param validator The <code>Validator</code> instance, used to access
	 *                  other field values.
	 * @param request Current request object.
	 * @return true if meets stated requirements, false otherwise.
	 * @throws Exception 
	 */
	public static boolean validateEarlyThan(Object bean,
			ValidatorAction va, Field field,
			ActionMessages errors,
			Validator validator,
			HttpServletRequest request) throws Exception {
		String compareToFiledName = field.getVarValue("earlyThan");
		long differ = 1L;
		//获取起止日期的值
		Object start = BeanHelper.getRawProperty(bean, field.getProperty());
		Object end = BeanHelper.getRawProperty(bean, compareToFiledName);
		if(start == null || end == null){
			return true;
		}  	
		if(start instanceof Date
				&& end instanceof Date 
				&& start != null 
				&& end != null){
			differ = ((Date)end).getTime() - ((Date)start).getTime();
		}else if(start instanceof String
				&& end instanceof String 
				&& !((String)start).trim().equals("")
				&& !((String)end).trim().equals("")){
			differ = BeanHelper.parseDate(String.valueOf(end)).getTime() - BeanHelper.parseDate(String.valueOf(start)).getTime();
		}
		if(differ >= 0){
			return true;
		}else{
			errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
			return false;
		}
	}

}
